<template>
  <div class="books-container">
    <!-- 搜索和过滤区域 -->
    <div class="search-section neu-card">
      <div class="search-form">
        <div class="search-input">
          <input 
            type="text" 
            v-model="searchQuery.keyword" 
            class="neu-input" 
            placeholder="搜索书名、作者或出版社"
            @keyup.enter="handleSearch"
          />
          <button class="neu-button primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </button>
        </div>
        
        <div class="filter-options">
          <div class="filter-item">
            <label>分类</label>
            <el-select v-model="searchQuery.category" placeholder="全部分类" class="filter-select">
              <el-option label="全部分类" value="" />
              <el-option 
                v-for="category in categories" 
                :key="category" 
                :label="category" 
                :value="category" 
              />
            </el-select>
          </div>
          
          <div class="filter-item">
            <label>状态</label>
            <el-select v-model="searchQuery.status" placeholder="全部状态" class="filter-select">
              <el-option label="全部状态" value="" />
              <el-option label="在馆" value="在馆" />
              <el-option label="借出" value="借出" />
            </el-select>
          </div>
          
          <button class="neu-button" @click="resetFilters">
            重置筛选
          </button>
        </div>
      </div>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="actions-section">
      <button class="neu-button primary" @click="showAddBookDialog">
        <el-icon><Plus /></el-icon>
        添加图书
      </button>
    </div>
    
    <!-- 图书列表 -->
    <div class="books-list neu-card">
      <el-table 
        :data="books" 
        style="width: 100%" 
        v-loading="loading"
        class="neu-table-wrapper"
      >
        <el-table-column prop="title" label="书名" min-width="150">
          <template #default="scope">
            <div class="book-title">
              <span>{{ scope.row.title }}</span>
              <span class="book-tag neu-tag" :class="scope.row.status === '在馆' ? 'green' : 'blue'">
                {{ scope.row.status }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" min-width="120" />
        <el-table-column prop="publisher" label="出版社" min-width="150" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="location" label="馆藏位置" min-width="120" />
        <el-table-column prop="borrowCount" label="借阅次数" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="table-actions">
              <button class="action-btn view" @click="viewBookDetails(scope.row)">
                <el-icon><View /></el-icon>
                详情
              </button>
              <button class="action-btn edit" @click="editBook(scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </button>
              <button class="action-btn delete" @click="confirmDeleteBook(scope.row)">
                <el-icon><Delete /></el-icon>
                删除
              </button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑图书对话框 -->
    <el-dialog
      v-model="bookDialogVisible"
      :title="isEditMode ? '编辑图书' : '添加图书'"
      width="600px"
      class="neu-dialog"
    >
      <el-form :model="bookForm" label-width="100px" :rules="bookRules" ref="bookFormRef">
        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="bookForm.isbn" placeholder="请输入ISBN" />
        </el-form-item>
        
        <el-form-item label="书名" prop="title">
          <el-input v-model="bookForm.title" placeholder="请输入书名" />
        </el-form-item>
        
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author" placeholder="请输入作者" />
        </el-form-item>
        
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="bookForm.publisher" placeholder="请输入出版社" />
        </el-form-item>
        
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
            v-model="bookForm.publishDate"
            type="date"
            placeholder="选择出版日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="bookForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option 
              v-for="category in categories" 
              :key="category" 
              :label="category" 
              :value="category" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="馆藏位置" prop="location">
          <el-input v-model="bookForm.location" placeholder="请输入馆藏位置" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="bookForm.description" 
            type="textarea" 
            rows="4"
            placeholder="请输入图书描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <button class="neu-button" @click="bookDialogVisible = false">取消</button>
          <button class="neu-button primary" @click="submitBookForm">确认</button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 图书详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="图书详情"
      width="600px"
      class="neu-dialog"
    >
      <div v-if="selectedBook" class="book-details">
        <div class="detail-item">
          <span class="label">ISBN:</span>
          <span class="value">{{ selectedBook.isbn }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">书名:</span>
          <span class="value">{{ selectedBook.title }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">作者:</span>
          <span class="value">{{ selectedBook.author }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">出版社:</span>
          <span class="value">{{ selectedBook.publisher }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">出版日期:</span>
          <span class="value">{{ selectedBook.publishDate }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">分类:</span>
          <span class="value">{{ selectedBook.category }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">馆藏位置:</span>
          <span class="value">{{ selectedBook.location }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">状态:</span>
          <span class="value" :class="selectedBook.status === '在馆' ? 'status-available' : 'status-borrowed'">
            {{ selectedBook.status }}
          </span>
        </div>
        
        <div class="detail-item">
          <span class="label">借阅次数:</span>
          <span class="value">{{ selectedBook.borrowCount }}</span>
        </div>
        
        <div class="detail-item full-width">
          <span class="label">描述:</span>
          <div class="description">{{ selectedBook.description }}</div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
      class="neu-dialog"
    >
      <div class="delete-confirm-content">
        <p>确定要删除《{{ selectedBook?.title }}》吗？</p>
        <p class="warning">此操作不可逆，请谨慎操作！</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <button class="neu-button" @click="deleteDialogVisible = false">取消</button>
          <button class="neu-button danger" @click="deleteBook">确认删除</button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, View, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { bookService } from '../api/services'

// 图书分类列表
const categories = [
  '文学', '科技', '历史', '艺术', '教育', '经济', '哲学', '社会科学'
]

// 图书列表数据
const books = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索和筛选条件
const searchQuery = reactive({
  keyword: '',
  category: '',
  status: ''
})

// 对话框控制
const bookDialogVisible = ref(false)
const detailsDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEditMode = ref(false)
const selectedBook = ref(null)
const bookFormRef = ref(null)

// 图书表单数据
const bookForm = reactive({
  isbn: '',
  title: '',
  author: '',
  publisher: '',
  publishDate: '',
  category: '',
  location: '',
  description: ''
})

// 表单验证规则
const bookRules = {
  isbn: [{ required: true, message: '请输入ISBN', trigger: 'blur' }],
  title: [{ required: true, message: '请输入书名', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  publisher: [{ required: true, message: '请输入出版社', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  location: [{ required: true, message: '请输入馆藏位置', trigger: 'blur' }]
}

// 获取图书列表
const fetchBooks = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchQuery
    }
    
    const response = await bookService.getBooks(params)
    if (response.code === 200) {
      books.value = response.data.books
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取图书列表失败')
    }
  } catch (error) {
    console.error('获取图书列表错误:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchBooks()
}

// 重置筛选条件
const resetFilters = () => {
  searchQuery.keyword = ''
  searchQuery.category = ''
  searchQuery.status = ''
  currentPage.value = 1
  fetchBooks()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchBooks()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchBooks()
}

// 显示添加图书对话框
const showAddBookDialog = () => {
  isEditMode.value = false
  resetBookForm()
  bookDialogVisible.value = true
}

// 查看图书详情
const viewBookDetails = (book) => {
  selectedBook.value = book
  detailsDialogVisible.value = true
}

// 编辑图书
const editBook = (book) => {
  isEditMode.value = true
  selectedBook.value = book
  Object.keys(bookForm).forEach(key => {
    if (key in book) {
      bookForm[key] = book[key]
    }
  })
  bookDialogVisible.value = true
}

// 确认删除图书
const confirmDeleteBook = (book) => {
  selectedBook.value = book
  deleteDialogVisible.value = true
}

// 删除图书
const deleteBook = async () => {
  try {
    const response = await bookService.deleteBook(selectedBook.value.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      fetchBooks()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除图书错误:', error)
    ElMessage.error('删除失败')
  }
}

// 重置图书表单
const resetBookForm = () => {
  Object.keys(bookForm).forEach(key => {
    bookForm[key] = ''
  })
  if (bookFormRef.value) {
    bookFormRef.value.resetFields()
  }
}

// 提交图书表单
const submitBookForm = async () => {
  if (!bookFormRef.value) return
  
  await bookFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (isEditMode.value) {
          // 编辑模式
          response = await bookService.updateBook(selectedBook.value.id, bookForm)
        } else {
          // 添加模式
          response = await bookService.addBook(bookForm)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEditMode.value ? '更新成功' : '添加成功')
          bookDialogVisible.value = false
          fetchBooks()
        } else {
          ElMessage.error(response.message || (isEditMode.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error(isEditMode.value ? '更新图书错误:' : '添加图书错误:', error)
        ElMessage.error(isEditMode.value ? '更新失败' : '添加失败')
      }
    }
  })
}

onMounted(() => {
  fetchBooks()
})
</script>

<style scoped>
@import '../assets/styles/neumorphism.css';

.books-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 搜索区域样式 */
.search-section {
  padding: 20px;
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.search-input {
  display: flex;
  gap: 10px;
}

.search-input .neu-input {
  flex: 1;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-end;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.filter-item label {
  font-size: 14px;
  color: var(--text-secondary);
}

.filter-select {
  width: 150px;
}

/* 操作按钮区域 */
.actions-section {
  display: flex;
  justify-content: flex-end;
}

/* 图书列表样式 */
.books-list {
  padding: 20px;
}

.neu-table-wrapper {
  border-radius: 10px;
  overflow: hidden;
}

.book-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.book-tag {
  font-size: 12px;
  padding: 2px 8px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.action-btn.view {
  background-color: var(--primary-blue-light);
  color: white;
}

.action-btn.edit {
  background-color: var(--primary-green-light);
  color: white;
}

.action-btn.delete {
  background-color: #ffcdd2;
  color: #d32f2f;
}

.action-btn:hover {
  opacity: 0.9;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 对话框样式 */
.neu-dialog :deep(.el-dialog) {
  border-radius: 15px;
  box-shadow: 
    10px 10px 20px var(--dark-shadow),
    -10px -10px 20px var(--light-shadow);
  background-color: var(--bg-color);
}

.neu-dialog :deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid var(--dark-shadow);
}

.neu-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.neu-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid var(--dark-shadow);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 图书详情样式 */
.book-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.detail-item {
  width: calc(50% - 8px);
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.detail-item.full-width {
  width: 100%;
}

.detail-item .label {
  font-weight: 500;
  color: var(--text-secondary);
  font-size: 14px;
}

.detail-item .value {
  font-size: 16px;
}

.status-available {
  color: var(--primary-green);
  font-weight: 500;
}

.status-borrowed {
  color: var(--primary-blue);
  font-weight: 500;
}

.description {
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.03);
  border-radius: 8px;
  min-height: 80px;
}

/* 删除确认对话框 */
.delete-confirm-content {
  text-align: center;
  padding: 10px 0;
}

.delete-confirm-content .warning {
  color: var(--danger);
  margin-top: 10px;
  font-weight: 500;
}

.neu-button.danger {
  background: linear-gradient(145deg, #ff7961, #f44336);
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-input {
    flex-direction: column;
  }
  
  .filter-options {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-select {
    width: 100%;
  }
  
  .detail-item {
    width: 100%;
  }
}
</style>